export class StorageBase {
    constructor(storage) {
        this.storage = storage;
    }
    /**
     * 设置缓存
     * @param {string} key
     * @param {any} val
     * @param {number} expire
     */
    set(key, val, expire = 0) {
        if (val === 'undefined' || val === 'null') {
            val = null;
        }
        var setData = {
            _flag: 1,
            data: val,
            time: Date.now(),
            type: typeof val
        };
        if (expire) {
            setData.expire = expire;
        }
        var cache = this.encrypt(JSON.stringify(setData));
        this.storage.setItem(key, cache);
    }
    /**
     * 获取缓存
     * @param {string} key
     * @param {boolean} all
     * @returns
     */
    get(key, all = false) {
        var getCache = this.storage.getItem(key);
        if (!getCache)
            return null;
        // 兼容获取直接使用 localStorage.setItem 设置的缓存值
        try {
            var cacheObj = JSON.parse(this.decrypt(getCache));
            if (!all && cacheObj._flag === 1) {
                return cacheObj.data;
            }
            else {
                return cacheObj;
            }
        }
        catch (error) {
            return getCache;
        }
    }
    /**
     * 删除指定的缓存
     * @param {string} key
     */
    remove(key) {
        this.storage.removeItem(key);
    }
    /**
     * 清空所有缓存
     */
    clear() {
        this.storage.clear();
    }
    /**
     * 加密
     * @param {string} data
     * @returns
     */
    encrypt(data) {
        return data;
    }
    /**
     * 解密
     * @param {string} data
     * @returns
     */
    decrypt(data) {
        return data;
    }
}

export const local = new StorageBase(localStorage);
export const session = new StorageBase(sessionStorage);